const mongoose = require('mongoose');
const qrqr = mongoose.model('qrqr');
const qrinfo = mongoose.model('qrinfo');
const { wrap: async } = require('co');
const msg = require('../../utils/message')
var multiparty = require('multiparty');
const fs = require('fs')
var qcos = require('../../utils/QCos')

/*********************************************** */
exports.create = async(function* (req, res) {
    console.log(req.body.data)
    let obj = JSON.parse(req.body.data)
    if (Object.keys(obj).length === 0) {
        return res.send(msg.genFailedMsg('body不能为空'))
    }
    let qr = new qrqr(obj);
    try {
        yield qr.updateAndSave();
        res.send(msg.genSuccessMsg('保存成功'))
    } catch (error) {
        console.log(error);
        res.send(msg.genFailedMsg('保存失败'))
    }
})
exports.update = async(function* (req, res) {
    try {

        console.log(JSON.stringify(req.body.data))
        let obj = JSON.parse(req.body.data)
        yield qrqr.remove({ getid: obj.getid })

        let qr = new qrqr(obj);
        try {
            yield qr.updateAndSave();
            res.send(msg.genSuccessMsg('保存成功'))
        } catch (error) {
            console.log(error);
            res.send(msg.genFailedMsg('保存失败'))
        }
    } catch (error) {
        console.log(error);
        res.send(msg.genFailedMsg('保存失败'))
    }
})
/*********************************************** */

//获取所有字段信息的名称
exports.getbyid = async(function* (req, res) {
    try {
        var index = yield qrqr.find(JSON.parse(`{ "getid": "${req.query.id}" }`)).exec()
        res.render('../views/index.ejs',
            {
                "html": `${index[0].html.toString('utf-8')}`,
                "pwd": index[0].pwd.toString('utf-8'),
                "ID": index[0].getid
            });
    } catch (error) {
        res.send(msg.genFailedMsg('获取失败', error))
    }
})

//获取所有字段信息的名称
exports.getbyid2 = async(function* (req, res) {
    try {
        var index = yield qrqr.find(JSON.parse(`{ "getid": "${req.query.id}" }`)).exec()
        res.send(msg.genSuccessMsg('获取成功', index))
    } catch (error) {
        res.send(msg.genFailedMsg('获取失败', error))
    }
})


exports.getinfo = async(function* (req, res) {
    try {
        var list = yield qrinfo.find(JSON.parse(`{ "id": "${req.query.id}" }`)).exec()
        res.send(list)
    } catch (error) {
        res.send(msg.genFailedMsg('获取失败', error))
    }
})

exports.setinfo = async(function* (req, res) {
    try {
        console.log(req.query.id + '------------' + req.query.txt)
        var _qrinfo = {
            "id": req.query.id,
            "txt": req.query.txt,
            "imgstr": req.query.img
        }
        var info = new qrinfo(_qrinfo)
        info.updateAndSave()
        res.send(msg.genSuccessMsg("成功"))
    } catch (error) {
        res.send(msg.genFailedMsg('获取失败', error))
    }
})

//获取字段列表
exports.getlist = async(function* (req, res) {
    try {
        var query = {
            page: parseInt(req.query.page) - 1,
            limit: parseInt(req.query.limit)
        }
        var list = yield qrqr.list(query);
        var count = yield qrqr.count();

        let nlst = list.map(i => {
            return {
                imgsrc: `http://120.27.139.133:3389/api/qrcode?id=${i.getid}`,
                html: i.html,//.length > 20 ? i.html.substring(0, 15) + '...' : i.html
                getid: i.getid,
                _id: i._id
            }
        })

        res.send(msg.genSuccessMsg('读取成功', nlst, { count: count }))
    } catch (error) {
        console.log(error);
        res.send(msg.genFailedMsg('获取失败'))
    }
})
//删除信息
exports.delinfobyid = async(function* (req, res) {
    try {
        console.log(req.query.id)
        let id = req.query.id;
        yield qrqr.remove({ "_id": id })
        res.send(msg.genSuccessMsg('删除成功'))
    } catch (error) {
        console.log(error);
        res.send(msg.genFailedMsg('删除失败'))
    }
})

//上传图片
exports.uploadfile = async(function* (req, res) {
    //生成multiparty对象，并配置上传目标路径
    var form = new multiparty.Form({ uploadDir: './static' });
    //上传完成后处理
    form.parse(req, function (err, fields, files) {
        console.log(err)
        var inputFile = files.file[0];
        var uploadedPath = inputFile.path;
        var dstPath = './static/' + inputFile.originalFilename;
        fs.rename(uploadedPath, dstPath, function (err) {
            if (err) {
                console.log('rename error: ' + err);
            } else {
                console.log('rename ok');
            }
        });
        files.file.path = dstPath;
        var data = files;
        qcos.upload(files.file.path, (err, result) => {
            if (err) {
                return res.send(msg.genFailedMsg(err))
            }
            res.send(msg.genSuccessMsg('成功', result));
            //删除本地?
        })
    });
})